package cn.acewill.yxd.yunxundian.componet.photoCrop;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.zyf.vc.ui.RecorderActivity;

import java.io.File;
import java.util.List;

import cn.acewill.yxd.yunxundian.BaseActivity;
import cn.acewill.yxd.yunxundian.R;
import cn.acewill.yxd.yunxundian.utils.MaterialDialogUtils;
import cn.acewill.yxd.yunxundian.utils.PermissionUtil;


public abstract class AbstractPhotoSelectedActivity extends BaseActivity  {
	public static final int REQUEST_CODE_CROP_PHOTO = 0x97;
	private static final int REQUEST_CODE_PHOTO = 0x98;
//	private static final int REQUEST_CODE_PICTURE = 0x99;
	private static final int REQUEST_CODE_PIC_KITKAT = 0x99;
	private static final int REQUEST_CODE_SELECT_PIC = 0x9a;

	public static final String RESULT_SELECTED_PHOTO_PATH = "resultSelectedPhotoPath";
	private static final int REQUEST_TAKE_VIDEO_CODE =0x9b ;
	private Dialog dialog;

	protected File captureFile;
	/** 保存裁剪后的图片路径 */
	private String photoPath = null;

	private boolean isScaleRatio = false;
	private DisplayMetrics metrics;
	/*根据此标识设置是否水印照片*/
	public static int label;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		WindowManager winManager = getWindowManager();
		metrics = new DisplayMetrics();
		winManager.getDefaultDisplay().getMetrics(metrics);
	}
	protected void popup(Context context, String photoPath, boolean isScaleRatio){
		this.isScaleRatio = isScaleRatio;
		popup(context, photoPath, 1);
	}
	
	@SuppressLint("InflateParams")
	protected void popup(Context context, String photoPath, int label) {
		AbstractPhotoSelectedActivity.label =label;
		this.photoPath = photoPath;
		LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		assert inflater != null;
		View holder = inflater.inflate(R.layout.view_popup_button,
				null, false);
		View gallery = holder.findViewById(R.id.btnPhoto);
		View capture = holder.findViewById(R.id.btnCapture);
		View cancel = holder.findViewById(R.id.btnCanel);

		ButtonClick click = new ButtonClick(this);
		gallery.setOnClickListener(click);// 图库选择
		capture.setOnClickListener(click);// 拍照选择
		cancel.setOnClickListener(click);// 取消
		dialog = PopupUtil.makePopup(context, holder);
		dialog.show();
	}
	protected void popup(Context context, String photoPath) {
		LayoutInflater inflater= (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View holder= null;
		if (inflater != null) {
			holder = inflater.inflate(R.layout.view_popup_button2,null,false);
			View cancel=holder.findViewById(R.id.btnCanel);
			View video=holder.findViewById(R.id.btnVideo);

			ButtonClick click = new ButtonClick(this);
			cancel.setOnClickListener(click);
			video.setOnClickListener(click);

			dialog=PopupUtil.makePopup(context,holder);
			dialog.show();
		}

	}


	public boolean checkCameraPermission() {
		boolean retBool = true;
		PackageManager pm = getPackageManager();
		boolean permission = (PackageManager.PERMISSION_GRANTED ==
				pm.checkPermission("android.permission.android.permission.CAMERA", "cn.acewill.yxd.yunxundian"));
		boolean permission1 = (PackageManager.PERMISSION_GRANTED ==
				pm.checkPermission("android.permission.RECORD_AUDIO", "cn.acewill.yxd.yunxundian"));
		if (!permission || !permission1) {
			BaseActivity.showAnimaDialog(AbstractPhotoSelectedActivity.this,"请开启设备相机访问和麦克风访问权限");
			retBool = false;
		}
		return retBool;
	}


	public class ButtonClick implements View.OnClickListener {

		private Context context;;

		private ButtonClick(Context context) {
			this.context = context;
		}

		@Override
		public void onClick(View v) {


			if (dialog != null) {
				dialog.dismiss();
			}
			if (v.getId() == R.id.btnPhoto) {// 图库选取
                checkTakeMediaPermission(R.id.btnPhoto);
			}

			if (v.getId() == R.id.btnCapture) {// 拍照
				// 从相册选取
                checkTakeMediaPermission(R.id.btnCapture);
			}
			/*视频录制*/
			if (v.getId()==R.id.btnVideo){
				// TODO: 2017/5/10  videorecord
				/*
				1.判断权限
				2.跳转拍摄
				 */
				checkTakeMediaPermission(R.id.btnVideo);
			}
			if (v.getId()==R.id.btn_cancel){
				dialog.dismiss();
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		switch (requestCode) {
//		case REQUEST_CODE_PICTURE://相册获取
//			if(data == null){
//				return;
//			}
//			String picturePath = getPhotoPathByLocalUri(this, data);
////			Bitmap mBitmap = BitmapUtils.getBmpFromFile(path,
////					metrics.widthPixels, metrics.heightPixels, null);
////			try {
////				mBitmap.compress(CompressFormat.JPEG, 100, new FileOutputStream(new File(photoPath)));
////			} catch (FileNotFoundException e) {
////				e.printStackTrace();
////			}
//			ImageUtil.cropPhotoSelf(this,picturePath, photoPath, isScaleRatio);
//			break;
		case REQUEST_CODE_SELECT_PIC:
			if (data == null) {
				return;
			}
			String picturePath = getPhotoPathByLocalUri(this, data);
			ImageUtil.cropPhotoSelf(this, picturePath, photoPath, isScaleRatio);
			break;
		case REQUEST_CODE_PIC_KITKAT:
			if (data == null) {
				return;
			}
			String picRealPath = getPath(this, data.getData());
			ImageUtil.cropPhotoSelf(this, picRealPath, photoPath, isScaleRatio);
			break;
		case REQUEST_CODE_PHOTO://手机拍照
			Bitmap bitmap = BitmapFactory.decodeFile(photoPath);
			if(bitmap == null){
				return;//如果把这个路径转换为bitmap图片失败，说明图片不存在
			}
			ImageUtil.cropPhotoSelf(this, photoPath,"", isScaleRatio);
			break;
		case ImageUtil.CROP_PHOTO:
			if(data == null){
				return;
			}
			String resultPath = data.getStringExtra(RESULT_SELECTED_PHOTO_PATH);
			onPhotoSelected(resultPath);
			break;
		default:
			break;
		}

/*
		if (requestCode==REQUEST_CODE_SELECT_PIC) {

			if (resultCode==this.RESULT_OK&&data!=null) {



				Uri selectedImage = data.getData();

				String[] filePathColumn = { MediaStore.Images.Media.DATA };





				Cursor cursor = this.getContentResolver().query(selectedImage,

						filePathColumn, null, null, null);

				cursor.moveToFirst();

				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);

				String picturePath = cursor.getString(columnIndex);

				cursor.close();

			}

		}
//4.4以上版本
		if (requestCode==REQUEST_CODE_PIC_KITKAT) {

			if (resultCode==this.RESULT_OK&&data!=null) {

				Uri selectedImage = data.getData();

				String picturePath = PictureHelper.getPath(this, selectedImage);



			}

		}
*/
	}

	/**
	 * 获取从本地图库返回来的时候的URI解析出来的文件路径
	 * 
	 * @return path
	 */
	private String getPhotoPathByLocalUri(Context context, Intent data) {
		Uri selectedImage = data.getData();
		String[] filePathColumn = { MediaStore.Images.Media.DATA };
		Cursor cursor = null;
		if (selectedImage != null) {
			cursor = context.getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
		}
//		if(cursor == null){
//			SystemToastDialog.showShortToast(context, ");
//			return;
//		}
		String picturePath = "";
		if (cursor != null) {
			cursor.moveToFirst();
			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			 picturePath = cursor.getString(columnIndex);
			cursor.close();
		}
		return picturePath;
	}
	/*权限的获取*/
	private void checkTakeMediaPermission(int typeId) {
		int permissionState_Camera = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
		int permissionState_Storage = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
		int permissionState_Audio = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO);
		if (permissionState_Camera != PackageManager.PERMISSION_GRANTED || permissionState_Storage != PackageManager.PERMISSION_GRANTED
				|| permissionState_Audio != PackageManager.PERMISSION_GRANTED) {
			// 用户已经拒绝过一次，给用户解释提示对话框
			if (ActivityCompat.shouldShowRequestPermissionRationale(this,
					Manifest.permission.CAMERA)) {
				// 展示自定义提醒框
				MaterialDialogUtils.showMaterialDialog(this, "你必须允许相应权限", "确定", "取消", true,true, new MaterialDialog.SingleButtonCallback() {
					@Override
					public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
						dialog.dismiss();
						PermissionUtil.requestPermissionForCamera(AbstractPhotoSelectedActivity.this);
					}
				}, new MaterialDialog.SingleButtonCallback() {
					@Override
					public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
						dialog.dismiss();
					}
				});
			}else{
				PermissionUtil.requestPermissionForCamera(this);
			}
		}else{
            if(typeId==R.id.btnVideo)
			skipToVideoTaker();
            else if(typeId==R.id.btnCapture)
            {
                Intent in = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.N)
                {
                    Uri uri = FileProvider.getUriForFile(this, getPackageName() + ".provider", new File(photoPath));
                    //通过Intent查找相关的Activity，更准确
                    List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(in, PackageManager.MATCH_DEFAULT_ONLY);
                    for (ResolveInfo resolveInfo : resInfoList) {
                        String packageName = resolveInfo.activityInfo.packageName;
                        grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    }
                    in.putExtra(MediaStore.EXTRA_OUTPUT,uri);
                }
                else
                {
                    in.putExtra(MediaStore.EXTRA_OUTPUT,
                            Uri.fromFile(new File(photoPath)));
                }
                in.putExtra("return-data", false);
                in.putExtra("outputFormat",
                        Bitmap.CompressFormat.JPEG.toString());
                startActivityForResult(in, REQUEST_CODE_PHOTO);

            }
            else if(typeId==R.id.btnPhoto)
            {
                Intent intent=new Intent(Intent.ACTION_GET_CONTENT);//ACTION_OPEN_DOCUMENT
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                intent.setType("image/jpeg");
                if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.KITKAT){
                    startActivityForResult(intent, REQUEST_CODE_PIC_KITKAT);
                }else{
                    startActivityForResult(intent, REQUEST_CODE_SELECT_PIC);
                }



            }
		}
	}
	/*跳转到拍摄*/
	private void skipToVideoTaker(){
		startActivityForResult(new Intent(this, RecorderActivity.class),REQUEST_TAKE_VIDEO_CODE);
	}

	/*判断权限是否存在*/
	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		// If request is cancelled, the result arrays are empty.
		if (grantResults.length > 0) {
			for (int grantResult : grantResults) {
				if (grantResult == PackageManager.PERMISSION_DENIED) {
					Toast.makeText(this, "没有权限", Toast.LENGTH_SHORT).show();
					return;
				}
			}
			switch (requestCode) {
				case PermissionUtil.CAMERA_STATE_REQUEST_CODE:
					//skipToVideoTaker();
					break;
			}
		} else {
			// permission denied, boo! Disable the
			// functionality that depends on this permission.
			Toast.makeText(this, "没有权限", Toast.LENGTH_SHORT).show();
		}
	}

	@SuppressLint("NewApi")
		public static String getPath(final Context context, final Uri uri) {

			final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

			// DocumentProvider
			if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
				// ExternalStorageProvider
				if (isExternalStorageDocument(uri)) {
					final String docId = DocumentsContract.getDocumentId(uri);
					final String[] split = docId.split(":");
					final String type = split[0];

	            if ("primary".equalsIgnoreCase(type)) {
	                return Environment.getExternalStorageDirectory() + "/" + split[1];
	            }

	            // TODO handle non-primary volumes
	        }
	        // DownloadsProvider
	        else if (isDownloadsDocument(uri)) {

	            final String id = DocumentsContract.getDocumentId(uri);
	            final Uri contentUri = ContentUris.withAppendedId(
	                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

	            return getDataColumn(context, contentUri, null, null);
	        }
	        // MediaProvider
	        else if (isMediaDocument(uri)) {
	            final String docId = DocumentsContract.getDocumentId(uri);
	            final String[] split = docId.split(":");
	            final String type = split[0];

	            Uri contentUri = null;
	            if ("image".equals(type)) {
	                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
	            } else if ("video".equals(type)) {
	                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
	            } else if ("audio".equals(type)) {
	                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
	            }

	            final String selection = "_id=?";
	            final String[] selectionArgs = new String[] {
	                    split[1]
	            };

	            return getDataColumn(context, contentUri, selection, selectionArgs);
	        }
	    }
	    // MediaStore (and general)
	    else if ("content".equalsIgnoreCase(uri.getScheme())) {

	        // Return the remote address
	        if (isGooglePhotosUri(uri))
	            return uri.getLastPathSegment();

	        return getDataColumn(context, uri, null, null);
	    }
	    // File
	    else if ("file".equalsIgnoreCase(uri.getScheme())) {
	        return uri.getPath();
	    }

	    return null;
	}

	/**
	 * Get the value of the data column for this Uri. This is useful for
	 * MediaStore Uris, and other file-based ContentProviders.
	 *
	 * @param context The context.
	 * @param uri The Uri to query.
	 * @param selection (Optional) Filter used in the query.
	 * @param selectionArgs (Optional) Selection arguments used in the query.
	 * @return The value of the _data column, which is typically a file path.
	 */
	public static String getDataColumn(Context context, Uri uri, String selection,
	        String[] selectionArgs) {

	    Cursor cursor = null;
	    final String column = "_data";
	    final String[] projection = {
	            column
	    };

	    try {
	        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
	                null);
	        if (cursor != null && cursor.moveToFirst()) {
	            final int index = cursor.getColumnIndexOrThrow(column);
	            return cursor.getString(index);
	        }
	    } finally {
	        if (cursor != null)
	            cursor.close();
	    }
	    return null;
	}


	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is ExternalStorageProvider.
	 */
	public static boolean isExternalStorageDocument(Uri uri) {
	    return "com.android.externalstorage.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is DownloadsProvider.
	 */
	public static boolean isDownloadsDocument(Uri uri) {
	    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is MediaProvider.
	 */
	public static boolean isMediaDocument(Uri uri) {
	    return "com.android.providers.media.documents".equals(uri.getAuthority());
	}

	/**
	 * @param uri The Uri to check.
	 * @return Whether the Uri authority is Google Photos.
	 */
	public static boolean isGooglePhotosUri(Uri uri) {
	    return "com.google.android.apps.photos.content".equals(uri.getAuthority());
	}

	public abstract void onPhotoSelected(String imgPath);

	//选取返回的结果


}